/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ua.yandex.threadpool;

/**
 *
 * @author Neophron
 */
public class ThreadPool {

    private final MyQueue<Runnable> queue;
    private final MyThread[] myThread;
    private final Thread[] threads;

    ThreadPool(int threadCount) {
        queue = new MyQueue<>();
        myThread = new MyThread[threadCount];
        threads = new Thread[threadCount];
        for (int i = 0; i < threadCount; i++) {
            myThread[i] = new MyThread(queue);
        }
        start();
    }

    private void start() {
        for (int i = 0; i < myThread.length; i++) {
            String s = Integer.toString(i);
            threads[i] = new Thread(myThread[i]);
            threads[i].setName("MyThreadPool-thread-" + s);
            threads[i].start();
        }
    }

    public void execute(Runnable r) {
        queue.add(r);
    }

    public boolean isWorking() {
        for (int i = 0; i < myThread.length; i++) {
            if (myThread[i].isWorking()) {
                return true;
            }
        }
        return false;
    }

    public void waitForFinishWork() throws InterruptedException {
        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                while (isWorking() || !queue.isEmpty()) {
                }
                for (int i = 0; i < threads.length; i++) {
                    threads[i].interrupt();
                }
            }
        });
        t.start();
        t.join();
    }

}
